package com.mh.mh.netty.closechannel;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * 客户端启动类
 */
public class AppClientHello {
    private final String host ;
    private final int port ;

    public AppClientHello(String host, int port){
        this.host = host;
        this.port = port;
    }


    public void run() throws InterruptedException {
        /**
         * 配置相应的参数，提供连结到远端的方法
         * // IO线程池
         */
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bs = new Bootstrap();// 客户端辅助启动类
            bs.group(group)
                    .channel(NioSocketChannel.class)// 实例化一个channel
                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new ChannelInitializer<SocketChannel>() {// 进行通道初始化配置
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // pipeline 是所有handler的容器，会一步步去执行handler
                            socketChannel.pipeline().addLast(new HandlerClientHelloClose());// 添加自定义的handler
                        }
                    });

            // 连接到远程节点，等待连接完成
            ChannelFuture future = bs.connect().sync();

            future.channel().writeAndFlush(Unpooled.copiedBuffer("hello world1", CharsetUtil.UTF_8));

            // 阻塞操作，closeFuture开启了一个channel的监听（这期间channel在进行各种操作），直到链路断开
//            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new AppClientHello("127.0.0.1", 7770).run();
    }


}
